Conditions in Python

Python has a very natural looking syntax for conditionals and boolean operations

if statment in Python

if True: do something


In [12]:
import random
toss = random.random() # returns a random value between 0 and 1
if toss > 0.5: 
    print 'I won'

if else statement


In [11]:
toss = random.random()
if toss > 0.5:
    print 'I won'
else:
    print 'You won'


I won

if - else if Statment

Python has the elif statement to represent an else if condition


In [19]:
fruits = ['apple', 'orange', 'banana', 'water melon']
fruit_index = random.randint(0, 3) # Get a random number between 0 and length of the fruit list
fruit = fruits[fruit_index] # use fruit_index as an index to randomly select a fruit
if fruit == 'apple':
    print 'red'
elif fruit == 'orange':
    print 'orange'
elif fruit == 'banana':
    print 'yellow'
else:
    print 'green'


yellow

In [ ]: